package com.qf.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 防止消息重复消费
 * @author 千锋健哥
 */
@Component
@RabbitListener(queues = "queue2")
public class Queue2Listener {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RabbitHandler
    public void messageHandler(Message msg, String str, Channel channel) throws Exception {
        //1. 获取消息的唯一标识
        long msgID = msg.getMessageProperties().getDeliveryTag();

        //2. 根据消息唯一标识通过setnx命令向redis中存入数据
        if (redisTemplate.opsForValue().setIfAbsent(String.valueOf(msgID), str, 5, TimeUnit.SECONDS)){
            //3. 能存入, 直接执行业务, 返回回执
            System.out.println("=======执行了业务, 消费了数据=========" + str);

        }
        //4. 直接返回回执
        channel.basicAck(msgID, true);

    }
}
